<template>
  <div>
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="ipagination"
      bordered
      @change="handleTableChange"
      rowKey="id"
    >
      <template
        v-for="col in [
          'defectDes',
          'defectType',
          'defectLevel',
          'riskImpact',
          'unit',
          'companyReply',
          'changeMeasure',
          'changeCase',
          'flowName',
        ]"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <a-input
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            @change="(e) => handleChange(e.target.value, record.id, col)"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <span slot="actionName">
        <a-button size="small" @click="handleTableRowAdd" :disabled="!isable || !(editingKey == '')" type="primary"
          >新增</a-button
        >
      </span>

      <span slot="action" slot-scope="text, record, index">
        <span v-if="record.editable">
          <a @click="saveTableData">保存</a>
          <a-divider type="vertical" />
          <a @click="cancel(record)">取消</a>
        </span>
        <span v-else>
          <a-button
            icon="edit"
            size="small"
            type="primary"
            @click="handleEdit(record)"
            :disabled="!isable || !(editingKey == '')"
            >编辑</a-button
          >
          <a-divider type="vertical" />
          <a-popconfirm :title="`确定要删除这项吗?`" @confirm="handleDel(record)">
            <a-button size="small" type="primary" :disabled="!isable || !(editingKey == '')" icon="delete"
              >删除</a-button
            >
          </a-popconfirm>
        </span>
      </span>
    </a-table>

    <a-row style="margin-top: 10px; text-align: center">
      <a-button size="small" @click="handleExportTemp">模版导出</a-button>
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :data="uploadParam"
        :headers="tokenHeader"
        :action="url.importExcelUrl"
        @change="handleImportExcel"
        accept=".docx, .doc, .xlsx, .xls, .pdf, .jpeg, .png"
      >
        <a-button
          size="small"
          type="primary"
          style="margin: 0 15px; background-color: #1ea489; border: 0"
          :disabled="!isable || !(editingKey == '')"
          >Excel导入</a-button
        >
      </a-upload>
      <!-- <a-button size="small" style="margin: 0 15px" @click="handleInput">导入</a-button> -->
      <a-button size="small" type="primary" style="margin-right: 15px" @click="handleExport">导出</a-button>
      <!-- TODO 预览 -->
      <a-button size="small" @click="handlePreview">在线预览</a-button>
    </a-row>

    <!-- <FileModel ref="fileModel" @openModelView="handleFileAdd"></FileModel> -->
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { columns4 } from '../indexColumns'
import { getAction, postAction, putAction, httpAction } from '../../../../../../api/manage'
import FileModel from '../FileModel.vue'
import { Base64 } from 'js-base64'

const dataSource = []
export default {
  mixins: [JeecgListMixin],
  props: ['planId', 'isable'],
  components: { FileModel },
  data() {
    return {
      columns: columns4(this),
      dataSource,
      selectedRows: [],
      url: {
        // list: '/sjzyzhgl/sjAuditOrg/list'
        list: '/incon/inconDefectTrack/queryInconDefectTrack',
        add: '/incon/inconDefectTrack/createDefectTrack',
        edit: '/incon/inconDefectTrack/edit',
        export: '/incon/inconDefectReview/exportByModuleFlag',
        del: '/incon/inconDefectTrack/deleteInconDefectTrack',
        exportTemp: '/incon/inconReviewPlan/downloadTemplate',
        // upload: '/incon/inconDefectReview/importExcel',
        importExcelUrl: `${window._CONFIG['domianURL']}/incon/inconDefectReview/importExcel`,
      },
      editingKey: '',
      target: {},
      uploadParam: {
        planId: this.planId,
        moduleFlag: 'track',
      },
      disableMixinCreated: true,
    }
  },
  methods: {
    // TODO 在线预览
    async handlePreview() {
      const data = await getAction(`${this.url.export}?planId=${this.planId}&moduleFlag=track`)
      if (data.code == 0) {
        let fileUrl = `${window._CONFIG['onlinePreviewFileURL']}/sys/common/download${data.result}`
        // let url = `${window._CONFIG['onlinePreviewDomainURL']}?url=${encodeURIComponent(fileUrl)}`
        let url = `${window._CONFIG['onlinePreviewDomainURL']}?url=${encodeURIComponent(Base64.encode(fileUrl))}`
        window.open(url, '_blank')
      }
    },
    handleInput() {
      this.$refs.fileModel.visible = true
    },
    async handleFileAdd(id) {
      // console.log(id,'id');
      const data = await postAction(`${this.url.upload}?planeId=${this.planId}&moduleFlag=track`)
      if (+data.code == 200) {
        this.$refs.fileModel.visible = false
        this.loadData()
      }
    },
    async handleExport() {
      const data = await getAction(`${this.url.export}?planId=${this.planId}&moduleFlag=track`)

      if (+data.code == 0) this.handleDownloadFile(data.result)
    },
    async handleExportTemp() {
      const data = await getAction(`${this.url.exportTemp}?planId=${this.planId}&moduleFlag=track`)

      if (+data.code == 0) this.handleDownloadFile(data.result)
    },
    // TODO 列表删除
    async handleDel(row) {
      const data = await putAction(`${this.url.del}?id=${row.id}`)
      if (+data.code == 200) this.loadData()
    },
    handleTableRowAdd() {
      this.dataSource.unshift({
        defectDes: '',
        defectType: '',
        defectLevel: '',
        riskImpact: '',
        unit: '',
        companyReply: '',
        changeMeasure: '',
        changeCase: '',
        flowName: '',
        editable: true,
      })
      this.editingKey = 'add'
    },
    handleEdit(record) {
      const newData = [...this.dataSource]
      const target = newData.find((item) => record.id === item.id)
      this.cacheTarget = Object.assign({}, target)
      this.target = Object.assign({}, target)
      if (target) {
        this.editingKey = record.id
        target.editable = true
        this.dataSource = newData
      }
    },
    handleDownloadFile(fileUrl) {
      this.$message.success('正在下载，请稍等！')
      let url = `${window._CONFIG['domianURL']}/sys/common/download/${fileUrl}`
      window.open(url, '_blank')
    },
    cancel({ id }) {
      if (id) {
        let i = 0
        for (; i < this.dataSource.length; i++) {
          const element = this.dataSource[i]
          if (element.id == id) {
            break
          }
        }
        this.dataSource.splice(i, 1, { ...this.cacheTarget })
      } else {
        this.dataSource.splice(0, 1)
      }
      this.editingKey = ''
    },
    // TODO
    handleChange(value, id, column) {
      console.log(value, id, column)
      const newData = [...this.dataSource]
      const target = newData.find((item) => id === item.id)
      if (target) {
        target[column] = value
        this.dataSource = newData
        this.target = target
      }
    },
    async saveTableData() {
      let param = {
        ...this.target,
        planId: this.planId,
      }
      let url = ''
      let methods = ''
      if (!this.target.id) {
        url = this.url.add
        methods = 'post'
      } else {
        url = this.url.edit
        methods = 'put'
      }
      const data = await httpAction(url, param, methods)
      if (+data.code != 200) {
        this.$message.error(data.message)
      } else {
        this.$message.success(data.message)
        this.editingKey = ''
        this.loadData()
        this.target = {}
      }
    },
  },
  watch: {
    planId: {
      handler(val) {
        this.url.list = `${this.url.list}?planId=${val}`
        this.loadData()
      },
      deep: true,
      immediate: true,
    },
  },
}
</script>

<style>
</style>
